package newkfp;

import Beans.AddedItem;
import Beans.Country_Factory;
import Beans.FactoryList;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import newkfp.util.JsfUtil;
import newkfp.util.PaginationHelper;

@ManagedBean(name = "exporterController")
@SessionScoped
public class ExporterController implements Serializable {

    private List<Exporter> listItems;
    Loger loger;
    @EJB
    private newkfp.LogFacade logFacade;
    @EJB
    private newkfp.TreausryFacade treausryFacade;
    private PaginationHelper paginationBills;
    private String exporterName = "";
    private Date fromDate;
    private Date toDate;
    private Exporter selectedExporter;
    private Exporter current;
    private DataModel items = null;
    private DataModel bill_items = null;
    @EJB
    private newkfp.ExporterFacade ejbFacade;
    @EJB
    private newkfp.FactoryFacade factoryFacade;
    private PaginationHelper pagination;
    private DataModel exportersBill = null;
    private int selectedItemIndex;
    private PaginationHelper paginationBill;
    private PaginationHelper country_factory;
    private DataModel factoryList = null;
    private DataModel exporter_factories_countries;
    private Boolean boolean1 = false;
    List<Country_Factory> country_FactoryLists_exporter = new ArrayList<Country_Factory>();   /// used when view page
    List<Country_Factory> country_FactoryLists_exporter_temp = new ArrayList<Country_Factory>(); // temp
    List<Country_Factory> country_FactoryLists = new ArrayList<Country_Factory>();
    @EJB
    private newkfp.ExporterCountryFacade exporter_countryfacad;
    @EJB
    private newkfp.ExporterFactoryFacade exporter_factoryfacad;
    @ManagedProperty(value = "#{exporterBillItemsController}")
    ExporterBillItems exporterBillItems;
    @EJB
    private BillItemFacade billItemFacade;

    public ExporterController() {
        loger = new Loger(getLogFacade());
    }

    public ExporterBillItems getExporterBillItems() {
        return exporterBillItems;
    }

    public void setExporterBillItems(ExporterBillItems exporterBillItems) {
        this.exporterBillItems = exporterBillItems;
    }

    public Exporter getSelected() {
        if (current == null) {
            current = new Exporter();
            selectedItemIndex = -1;
        }
        return current;
    }

    private ExporterFacade getFacade() {
        return ejbFacade;
    }

    public PaginationHelper getPagination() {
        if (pagination == null) {
            pagination = new PaginationHelper(getFacade().count()) {

                @Override
                public int getItemsCount() {
                    return getFacade().count();
                }

                @Override
                public DataModel createPageDataModel() {
                    return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
                }
            };
        }
        return pagination;
    }

    public PaginationHelper getBillItemPagination() {
        if (paginationBills == null) {
            paginationBills = new PaginationHelper(10) {

                @Override
                public int getItemsCount() {
                    return getFacade().count();
                }

                @Override
                public DataModel createPageDataModel() {
                    Calendar calendar = Calendar.getInstance();
                    if (toDate != null) {
                        calendar.setTime(toDate);
                        calendar.add(Calendar.DAY_OF_MONTH, 1);
                    }
                    return new ListDataModel(getFacade().getExporterBillAtPeriod(getSelectedExporter().getIdExporter(), fromDate, calendar.getTime()));
                }
            };
        }
        return paginationBills;
    }

    public String prepareList() {
        recreateModel();
        return "CreateExporter";
    }

    public String prepareView(Exporter exporter) {
        current = exporter;
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        country_FactoryLists_exporter = getFactory_countryByExporter();

        System.out.println(" number of country is" + country_FactoryLists_exporter.size());
        for (Iterator<Country_Factory> it = country_FactoryLists_exporter.iterator(); it.hasNext();) {
            Country_Factory country_Factory = it.next();

            if (country_Factory.getFactoryList().size() > 0) {
                System.out.println(" number of factory in this country greater than 1 " + country_Factory.getFactoryList().size());
                country_FactoryLists_exporter_temp.add(country_Factory);

            }



        }
        System.out.println(" number of country that conatins factory is " + country_FactoryLists_exporter_temp.size());
        country_FactoryLists_exporter = null;

        country_FactoryLists_exporter = country_FactoryLists_exporter_temp;
        System.out.println(" after initialization again " + country_FactoryLists_exporter.size());
        if (current.getBalance() > 0) {
            boolean1 = true;
        } else {
            boolean1 = false;
        }
        return "View";
    }

    public String prepareCreate() {
        current = new Exporter();
        selectedItemIndex = -1;
        recreateModel();
        return "CreateExporter";
    }

    public String create() {
        loger = new Loger(getLogFacade());
        try {
            current.setTempFlag(0);
            if (!getBoolean1()) {
                current.setBalance(current.getBalance() * -1);
            }
            getFacade().create(current);

            //   country_FactoryLists
            for (Iterator<Country_Factory> it = country_FactoryLists.iterator(); it.hasNext();) {
                Country_Factory country_Factory = it.next();

                if (country_Factory.getSelected()) {

                    ExporterCountry newExporterCountry = new ExporterCountry();

                    newExporterCountry.setIdExporter(current);
                    newExporterCountry.setIdcountry(new Country(country_Factory.getCountryID()));

                    exporter_countryfacad.create(newExporterCountry);
                    List factories = country_Factory.getFactoryList();
                    for (Iterator it1 = factories.iterator(); it1.hasNext();) {
                        FactoryList object = (FactoryList) it1.next();
                        if (object.getSelected()) {

                            ExporterFactory exporter_factory = new ExporterFactory();

                            exporter_factory.setIdexporter(current);
                            exporter_factory.setIdfactory(new Factory(object.getFactoryId()));

                            exporter_factoryfacad.create(exporter_factory);
                            System.out.println(" -----------------------factory selectedd " + object.getFactoryName());
                        }

                    }
                }

            }

            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("ExporterCreated"));
            loger.LogerString("اضافة مورد جديد", 0);
            recreateModel();
//            Treausry treausry = new Treausry();
//            treausry.setActionDate(new Date());
//            treausry.setCustomerId(null);
//            HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
//            treausry.setEmployeeId(new Employee(Integer.parseInt( session.getValue("empid").toString())));
//            treausry.setExporterId(current);
//            treausry.setGeneralDescription("");
//            treausry.setMoneyAmount(current.getBalance());
//            treausryFacade.create(treausry);
            return prepareCreate();
        } catch (Exception e) {
            loger.LogerString("خطاء في اضافة مورد جديد", 1);
            loger.LogerString("ExporterController : Create : " + e.getMessage(), -1);

            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));

            return null;
        }
    }

    public String prepareEdit(Exporter exporter) {
        current = exporter;
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        if (current.getBalance() > 0) {
            boolean1 = true;
        } else {
            boolean1 = false;
            current.setBalance(current.getBalance() * -1);
        }
        return "Edit";
    }

    public String update() {
        loger = new Loger(getLogFacade());
        System.out.println("update");
        try {
            getFacade().edit(current);
            if (!getBoolean1()) {
                System.out.println("ffffffff");
                current.setBalance(current.getBalance() * -1);
            }
            getFacade().edit(current);
            System.out.println("updated");
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("ExporterUpdated"));
            loger.LogerString(" تم تعديل مورد بنجاح", 0);
            return "View";
        } catch (Exception e) {
            loger.LogerString("خطاء في تعديل مورد", 1);
            loger.LogerString("ExporterController : update : " + e.getMessage(), -1);
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            e.printStackTrace();
            return null;
        }
    }

    public String destroy(Exporter exporter) {
        current = exporter;
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        performDestroy();
        recreatePagination();
        recreateModel();
        return "CreateExporter";
    }

    public String destroyAndView() {
        performDestroy();
        recreateModel();
        updateCurrentItem();
        if (selectedItemIndex >= 0) {
            return "View";
        } else {
            // all items were removed - go back to list
            recreateModel();
            return "CreateExporter";
        }
    }

    private void performDestroy() {
        loger = new Loger(getLogFacade());
        try {
            getFacade().remove(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("ExporterDeleted"));
            loger.LogerString("تم حذف المورد بنجاح", 0);
        } catch (Exception e) {
            loger.LogerString("خطاء في حذف المورد", 1);
            loger.LogerString("ExporterController : Destroy : " + e.getMessage(), -1);
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
        }
    }

    private void updateCurrentItem() {
        int count = getFacade().count();
        if (selectedItemIndex >= count) {
            // selected index cannot be bigger than number of items:
            selectedItemIndex = count - 1;
            // go to previous page if last page disappeared:
            if (pagination.getPageFirstItem() >= count) {
                pagination.previousPage();
            }
        }
        if (selectedItemIndex >= 0) {
            current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex + 1}).get(0);
        }
    }

    public DataModel getItems() {
        clearSession();
        if (items == null) {
            items = getPagination().createPageDataModel();
        }
        return items;
    }

    private void recreateModel() {
        items = null;
        pagination = null;
    }

    private void recreatePagination() {
        pagination = null;
    }

    public String next() {
        getPagination().nextPage();
        recreateModel();
        return "CreateExporter";
    }

    public String previous() {
        getPagination().previousPage();
        recreateModel();
        return "CreateExporter";
    }

    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
    }

    @FacesConverter(forClass = Exporter.class)
    public static class ExporterControllerConverter implements Converter {

        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            ExporterController controller = (ExporterController) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "exporterController");
            return controller.ejbFacade.find(getKey(value));
        }

        java.lang.Integer getKey(String value) {
            java.lang.Integer key;
            key = Integer.valueOf(value);
            return key;
        }

        String getStringKey(java.lang.Integer value) {
            StringBuffer sb = new StringBuffer();
            sb.append(value);
            return sb.toString();
        }

        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof Exporter) {
                Exporter o = (Exporter) object;
                return getStringKey(o.getIdExporter());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + ExporterController.class.getName());
            }
        }
    }

    public DataModel getExportersBill() {
        exportersBill = null;
        if (exportersBill == null) {
            System.out.println(" getting exporter Bill ");
            exportersBill = getPaginationBill().createPageDataModel();
        }
        return exportersBill;

    }

    public PaginationHelper getPaginationBill() {

        paginationBill = null;

        if (paginationBill == null) {
            System.out.println("pagination is null  ");
            paginationBill = new PaginationHelper(10) {

                @Override
                public int getItemsCount() {
                    System.out.println(" coutnt ====" + getFacade().count());
                    return getFacade().count();
                }

                @Override
                public DataModel createPageDataModel() {
                    System.out.println(" getting bill for  selected index createPage " + selectedItemIndex);
                    List list = getFacade().getBillsExporter(current.getIdExporter());
                    for (Iterator it = list.iterator(); it.hasNext();) {
                        Bill object = (Bill) it.next();
                        System.out.println(" list cont" + object.getBillTotal());

                    }
                    return new ListDataModel(list);
                }
            };
        }
        return paginationBill;

    }

    public String bills(Exporter exporter) {
        current = exporter;
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "ExporterBills";
    }
    /////////////////////////////////////////////////////////======

    public PaginationHelper getCountry_factory() {
        country_factory = null;
        if (country_factory == null) {
            country_factory = new PaginationHelper(10) {

                @Override
                public int getItemsCount() {
                    return getFacade().count();
                }

                @Override
                public DataModel createPageDataModel() {
                    country_FactoryLists.clear();
                    List<Country> countrys = ejbFacade.getAllCountry();
                    for (Iterator it = countrys.iterator(); it.hasNext();) {
                        Country country = (Country) it.next();
                        List<FactoryList> factoryLists = new ArrayList<FactoryList>();
                        //List<Factory> list=   ejbFacade.getfactorybyCountryid(country.getIdcountry());
                        Collection<Factory> list = factoryFacade.getFactoryOfCountryById(country);
                        for (Iterator<Factory> it1 = list.iterator(); it1.hasNext();) {
                            Factory factory = it1.next();
//                                   System.out.println(" time log for project "+project.getProId()+"  worked hour : "+timeLog.getWorkedHours());
                            FactoryList factoryList = new FactoryList();

                            // fill shadow been 
                            factoryList.setFactoryId(factory.getIdFactory());
                            factoryList.setFactoryName(factory.getFactoryName());
                            factoryLists.add(factoryList);
                        }

                        Country_Factory country_Factory = new Country_Factory();
                        country_Factory.setCountryID(country.getIdcountry());
                        country_Factory.setCountryName(country.getCountryName());
                        country_Factory.setFactoryList(factoryLists);
                        country_FactoryLists.add(country_Factory);
                    }

                    return new ListDataModel(country_FactoryLists);
                }
            };
        }
        return country_factory;
    }

    public DataModel getFactoryList() {


        factoryList = getCountry_factory().createPageDataModel();


        return factoryList;

    }
    ///////A7med Kotb//////////////

    public String getExporterName() {
        return exporterName;
    }

    public void setExporterName(String exporterName) {
        this.exporterName = exporterName;
    }

    ////////A7med Kotb//////////////
    public List<String> autocomplete(String inputValue) {
        System.out.println("//Search Text: " + inputValue);
        List<Exporter> objList = getFacade().searchExporters(inputValue);
        List<String> exporterNames = new ArrayList<String>();
        for (Iterator<Exporter> it = objList.iterator(); it.hasNext();) {
            Exporter cust = it.next();
            exporterNames.add(cust.getExporterName());
        }
        return exporterNames;
    }

    public Exporter getSelectedExporter() {
        selectedExporter = getFacade().getExporterByName(getExporterName());

        return selectedExporter;
    }

    public void setSelectedExporter(Exporter selectedExporter) {
        this.selectedExporter = selectedExporter;
    }

    public Date getToDate() {
        return toDate;
    }

    public void setToDate(Date toDate) {
        this.toDate = toDate;
    }

    public DataModel getBill_items() {
        paginationBills = null;
        bill_items = null;
        if (getSelectedExporter() != null) {
            bill_items = getBillItemPagination().createPageDataModel();
        }
        return bill_items;
    }

    public void setBill_items(DataModel bill_items) {
        this.bill_items = bill_items;
    }

    public String prepareBillItemList() {
        recreateModel();
        return "gard_exporter";
    }

    public String nextBillItem() {
        getPaginationBills().nextPage();
        recreateModel();
        return "gard_exporter";
    }

    public String previousBillItem() {
        getPaginationBills().previousPage();
        recreateModel();
        return "gard_exporter";
    }

    public PaginationHelper getPaginationBills() {
        return paginationBills;
    }

    public void setPaginationBills(PaginationHelper paginationBills) {
        this.paginationBills = paginationBills;
    }

    public Double getBillTotal() {
        return getFacade().getBillTotal();
    }

    public Double getBillCach() {
        return getFacade().getBillCach();
    }

    public Double getBillRemainder() {
        return getFacade().getBillRemain();
    }

    public Double getDiscount() {
        return getFacade().getBillDisCount();
    }

    public Date getFromDate() {
        return fromDate;
    }

    public void setFromDate(Date fromDate) {
        this.fromDate = fromDate;
    }

    public List<Country_Factory> getFactory_countryByExporter() {


        List<ExporterFactory> factories = exporter_factoryfacad.getFactoriesByExporterId(current.getIdExporter());



        List<Country> countrys = ejbFacade.getAllCountry();
        for (Iterator it = countrys.iterator(); it.hasNext();) {
            Country country = (Country) it.next();
            List<FactoryList> factoryLists = new ArrayList<FactoryList>();
            //List<Factory> list=   ejbFacade.getfactorybyCountryid(country.getIdcountry());
            Collection<Factory> list = country.getFactoryCollection();
            for (Iterator<Factory> it1 = list.iterator(); it1.hasNext();) {
                Factory factory = it1.next();
                for (Iterator<ExporterFactory> it2 = factories.iterator(); it2.hasNext();) {
                    ExporterFactory exporterFactory = it2.next();

                    if (exporterFactory.getIdfactory().getIdFactory() == factory.getIdFactory()) {
                        FactoryList factoryList = new FactoryList();
                        factoryList.setFactoryId(factory.getIdFactory());
                        factoryList.setFactoryName(factory.getFactoryName());
                        factoryLists.add(factoryList);
                    }
                }
            }

            Country_Factory country_Factory = new Country_Factory();
            country_Factory.setCountryID(country.getIdcountry());
            country_Factory.setCountryName(country.getCountryName());
            country_Factory.setFactoryList(factoryLists);
            country_FactoryLists_exporter.add(country_Factory);
        }
        return country_FactoryLists_exporter;
    }

    public DataModel getExporter_factories_countries() {
        return new ListDataModel(country_FactoryLists_exporter);
    }

    public LogFacade getLogFacade() {
        return logFacade;
    }

    public void setLogFacade(LogFacade logFacade) {
        this.logFacade = logFacade;
    }

    public FactoryFacade getFactoryFacade() {
        return factoryFacade;
    }

    public void setFactoryFacade(FactoryFacade factoryFacade) {
        this.factoryFacade = factoryFacade;
    }

    public TreausryFacade getTreausryFacade() {
        return treausryFacade;
    }

    public void setTreausryFacade(TreausryFacade treausryFacade) {
        this.treausryFacade = treausryFacade;
    }

    public Boolean getBoolean1() {
        if (selectedExporter != null && selectedExporter.getBalance() < 0) {
            boolean1 = true;
        }
        return boolean1;
    }

    public void setBoolean1(Boolean boolean1) {
        this.boolean1 = boolean1;
    }

    public void clearSession() {
        Map m = FacesContext.getCurrentInstance().getExternalContext().getSessionMap();
//    m.remove("exporterController");   

        m.remove("employeeController");
        m.remove("customerController");
        m.remove("countryController");
        m.remove("billInformationController");
        m.remove("inventoryStoreController");
        m.remove("moneyController");
        m.remove("billConfirmController");
        m.remove("billExporterInformationController");
        m.remove("logController");
        m.remove("itemController");

    }

    /*
     * View Exporter Bill Details
     */
    public String viewExporterBill(Bill bill) {
        exporterBillItems.setBillNumber(bill.getBillNumber());
        exporterBillItems.setDocNumber(bill.getDocNum());
        exporterBillItems.setExporterName(bill.getExporterID().getExporterName());
        exporterBillItems.setSelectedExporter(bill.getExporterID());
        exporterBillItems.setBillTotal(bill.getBillTotal());
        exporterBillItems.setPaied(bill.getBillCach());
        exporterBillItems.setBill_reminder(bill.getBillReminder());
        exporterBillItems.setAdd_Item(createAddedItemList(getBillItemFacade().getItemsByBillId(bill.getIdBill())));
        exporterBillItems.setBill(bill);
        exporterBillItems.setBillDate(bill.getCreateDate());
        return "viewExporterBill";
    }

    private ArrayList<AddedItem> createAddedItemList(Collection<BillItem> billItems) {
        ArrayList<AddedItem> addedItems = new ArrayList<AddedItem>();
        for (BillItem billItem : billItems) {
            if (billItem.getExportBill() == 1) {
                addedItems.add(new AddedItem(billItem.getFactoryID().getIdcountry().getCountryName(), billItem.getFactoryID().getFactoryName(), billItem.getItemID().getItemName(), billItem.getItemPrice(), billItem.getTotalPrice(), billItem.getPackageCount(), billItem.getItemAmount(), null, false, billItem.getBillItemStatus()));
            } else {
                addedItems.add(new AddedItem(billItem.getFactoryID().getIdcountry().getCountryName(), billItem.getFactoryID().getFactoryName(), billItem.getItemID().getItemName(), billItem.getItemPrice(), billItem.getTotalPrice(), billItem.getPackageCount(), billItem.getItemAmount(), null, true, billItem.getBillItemStatus()));
            }
        }
        return addedItems;
    }

    public BillItemFacade getBillItemFacade() {
        return billItemFacade;
    }

    public void setBillItemFacade(BillItemFacade billItemFacade) {
        this.billItemFacade = billItemFacade;
    }

    public List<Exporter> getListItems() {
        List<Exporter> exporters = (List<Exporter>) ((javax.faces.model.DataModel) getItems()).getWrappedData();
        exporters.remove(new Exporter(0));
        exporters.remove(new Exporter(-1));
        return exporters;
    }

    public void setListItems(List<Exporter> listItems) {
        this.listItems = listItems;
    }
}
